import AuthAPI, { type LoginData } from "@/api/auth";
import UserAPI, { type User } from "@/api/user";
import { resetRouter } from "@/router";
import { store } from "@/store";
import { TOKEN_KEY } from "@/enums/CacheEnum";
import { JWTparse } from "@/utils";

export const useUserStore = defineStore("user", () => {
  const user = ref<User>({
    id: 0,
    userName: "",
    realName: "",
    password: "",
    gender: 0,
    grade: 0,
    isAdmin: 0,
    picture: "",
  });

  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      AuthAPI.login(loginData)
        .then((data) => {
          const accessToken = data;
          localStorage.setItem(TOKEN_KEY, accessToken as string); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getUserInfo() {
    return new Promise<User>((resolve, reject) => {
      const { sub } = JWTparse(localStorage.getItem(TOKEN_KEY) as string);

      UserAPI.searchById({ id: sub })
        .then((data) => {
          if (data[0]) {
            Object.assign(user.value, { ...data[0] });
            resolve(data[0]);
          } else {
            reject("未知错误");
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // user logout
  function logout() {
    return new Promise<void>((resolve, reject) => {
      AuthAPI.logout()
        .then(() => {
          localStorage.setItem(TOKEN_KEY, "");
          location.reload(); // 清空路由
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // remove token
  function resetToken() {
    return new Promise<void>((resolve) => {
      localStorage.setItem(TOKEN_KEY, "");
      resetRouter();
      resolve();
    });
  }

  return {
    user,
    login,
    getUserInfo,
    logout,
    resetToken,
  };
});

/**
 * 用于在组件外部（如在Pinia Store 中）使用 Pinia 提供的 store 实例。
 * 官方文档解释了如何在组件外部使用 Pinia Store：
 * https://pinia.vuejs.org/core-concepts/outside-component-usage.html#using-a-store-outside-of-a-component
 */
export function useUserStoreHook() {
  return useUserStore(store);
}
